package ub.pis;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import ub.pis.net.Goear;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class Pant4 extends Activity {
	private Intent i;
	private ListView c;
	private ArrayList<String> cancons = new ArrayList<String>();
	private Bundle bundle;
	private BDArtista db;
	String titulo, artista, url, titol_actual;
	int puntuacio;
	
	/** Conector al servicio*/
	private InterficieMedia mpInterface;

	private ServiceConnection mConnection = new ServiceConnection(){
		public void onServiceConnected(ComponentName className, IBinder service){
			mpInterface = InterficieMedia.Stub.asInterface(service);
			Log.i("SERVICESTATE","serviceConnected");
		}
		public void onServiceDisconnected(ComponentName className) {
			Log.e("SERVICESTATE", "Service has unexpectedly disconnected");
			mpInterface = null;
		}
	};
	
	private void startService(){
		Intent svc = new Intent(this,MediaService.class);
		startService(svc);
	}
	
	private void bindService(){
		this.bindService(new Intent(Pant4.this,MediaService.class),
				mConnection, Context.BIND_AUTO_CREATE);
	}
	
	private void unBind(){
		this.unbindService(mConnection);
	}

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pant4);
		
		bindService();
		
		db = new BDArtista(this);
		
		show_artist();
		
		omplirLlista(artista);

		/*
		 *  Seleccionar cancion de la lista 
		 */
		c.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, android.view.View v,
					int position, long id) {
				
				titulo = cancons.get(position);
							
				// Busca la nueva URL de la cancion y la actualiza en DB
				Goear g = new Goear(artista, titulo);
				try {
					if(g.searchSong()){
						url = g.getMp3_url();
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
				// Setea la cancion que va a sonar y inicia la reproduccion.
				try {
					mpInterface.stop();
					mpInterface.playFile(titulo);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				
				// Desconectamos pant4 del servicio.
				startService();
				unBind();
				
				// Solo damos el titulo de la cancion que suena
				// y la pantalla de donde proviene.
				
				Bundle b = new Bundle();
				b.putString("TITOL", titulo);
				b.putInt("PANTALLA", 4);
				i = new Intent(Pant4.this, Pant2.class);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});

		// Volver a la actividad anterior
		ImageButton btnVolver = (ImageButton) findViewById(R.id.btnBackCanc);
		btnVolver.setOnClickListener(new View.OnClickListener() {
			//@Override
			public void onClick(View v) {
				Bundle b = new Bundle();
				b.putInt("PANTALLA", 4);
				b.putString("TITOL", titol_actual);
				i = new Intent(Pant4.this, Pant3.class);
				i.putExtras(b);
				startActivity(i);
				finish();
			}
		});
	}
	
	/**
	 * Creem un ContextMenu on es mostrara si volem vetar la canco o desvetar.
	 */
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
    	if(v.getId()==R.id.lstCanciones) {	
    		super.onCreateContextMenu(menu, v, menuInfo);
    		
    		AdapterView.AdapterContextMenuInfo info =
                (AdapterView.AdapterContextMenuInfo)menuInfo;
    		
    		String selected = c.getAdapter().getItem(info.position).toString();
    		Log.i("SELECTED",selected);
    		db.open();
    		if(db.isVetatS(selected)){
    			selected += " disabled";
    		}
    		else{
    			selected += " enabled";
    		}
    		db.close();
    		
    		MenuInflater inflater = getMenuInflater();
    		menu.setHeaderTitle(selected);
    	 
    	        inflater.inflate(R.layout.menu_b, menu);
    	}
    }
	
	/**
     * En el ContextMenu seleccionarem si volem vetar o no a la canco
     */
	public boolean onContextItemSelected(MenuItem item) {
		
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    db.open();
	    switch (item.getItemId()) {
	        case R.id.Opc1:
	        	Log.i("OPC1","pulsada");
	        	Log.i("Artista",cancons.get(info.position));
	        	db.actualitzarPuntuacio(cancons.get(info.position), -1);
	        	db.close();
	            return true;
	        case R.id.Opc2:
	        	Log.i("OPC2","pulsada");
	        	db.actualitzarPuntuacio(cancons.get(info.position), 3);
	        	db.close();
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}	

	/** 
	 * Mostrar artista en el txtView
	 */
	public void show_artist() {
		TextView nomArtista = (TextView) findViewById(R.id.txtArtista);
		bundle = new Bundle();
		bundle = this.getIntent().getExtras();
		artista = bundle.getString("NOMBRE");
		titol_actual = bundle.getString("TITOL");
		nomArtista.setText(artista);
	}
	
	/**
	 * Omple la llista de cancons d'un artista
	 * @param artista
	 */
	
	private void omplirLlista(String artista) {
		db.open();
		Cursor cur = db.getCancons(artista);
		startManagingCursor(cur);
		//Comprovem que hi ha com a minim un registre
		if(cur.moveToFirst()) {
			do {
				cancons.add(cur.getString(0));
			}while(cur.moveToNext());
			
		}
		cur.close();
		c = (ListView) findViewById(R.id.lstCanciones);
		c.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, cancons));
		registerForContextMenu(c);	
		db.close();

	}
}
